package com.ljvm.sms;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

/**
 * Created by user on 2017/6/30.
 */
public class SendSms {

    public static final String PRODUCT = "Dysmsapi";
    public static final String DOMAIN = "dysmsapi.aliyuncs.com";
    public static final String REGIONID = "cn-hangzhou";

    private String accessKeyId;
    private String accessKeySecret;
    private String signName;
    private String msg;

    public String getMsg() {
        return msg;
    }

    public SendSms(String accessKeyId, String accessKeySecret, String signName) {
        this.accessKeyId = accessKeyId;
        this.accessKeySecret = accessKeySecret;
        this.signName = signName;
    }

    /**
     *
     * @param phone (split with "," and no more than 20)
     * @param SmsTemplateCode
     * @param body （json string）
     * @return
     */
    public boolean sendSms(String phone, String SmsTemplateCode, String body) {
        IClientProfile profile = DefaultProfile.getProfile(REGIONID, accessKeyId, accessKeySecret);
        try {
            DefaultProfile.addEndpoint(REGIONID, REGIONID, PRODUCT, DOMAIN);
        } catch (ClientException e) {
            e.printStackTrace();
            return false;
        }
        IAcsClient client = new DefaultAcsClient(profile);
        SendSmsRequest request = new SendSmsRequest();
        request.setSignName(signName);
        request.setTemplateCode(SmsTemplateCode);
        request.setTemplateParam(body);
        request.setPhoneNumbers(phone);
        try {
            SendSmsResponse httpResponse = client.getAcsResponse(request);
            if ("OK".equals(httpResponse.getCode())) {
                return true;
            }
            this.msg = httpResponse.getMessage();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }

}
